<template>
	<el-dialog
		:visible.sync="dialogVisible"
		:title="''"
		fullscreen
		:show-close="false"
		:close-on-press-escape="false"
		:close-on-click-modal="false"
		custom-class="pagePop"
		:before-close="handleClose"
	>
		<div class="inner">
			<div class="head">
				<div class="left">
					<img class="icon" src="" alt="" />
					<span>{{ title }}</span>
				</div>
				<div class="right">
					<!-- <el-button class="right-button-1">就绪</el-button> -->
					<el-button @click="handleClose" class="right-button-2">关闭</el-button>
				</div>
			</div>
			<div class="body">
				<div class="left">
					<div class="card card-1">
						<div class="title">1.客户信息</div>
						<el-form class="custom-form" disabled ref="form" label-position="top" :model="form" label-width="80px">
							<el-row :gutter="16">
								<el-col :span="12">
									<el-form-item label="姓名">
										<el-input v-model="form.user_name" suffix-icon="el-icon-search"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="出生日期">
										<el-date-picker style="width: 100%" v-model="form.birthday" value-format="yyyy-MM-dd" type="date" placeholder=""></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="性别">
										<el-select style="width: 100%" v-model="form.gender" placeholder="">
											<el-option label="男" :value="1"></el-option>
											<el-option label="女" :value="2"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<!-- <el-col :span="12">
									<el-form-item label="编号">
										<el-input v-model="form.name"></el-input>
									</el-form-item>
								</el-col> -->
								<el-col :span="12">
									<el-form-item label="体重">
										<el-input v-model="form.weight">
											<template slot="suffix">kg</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="身高">
										<el-input v-model="form.height">
											<template slot="suffix">cm</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</div>
					<div class="card card-2">
						<div class="title">2.检测信息</div>
						<el-form class="custom-form" disabled ref="form" label-position="top" :model="form" label-width="80px">
							<el-row :gutter="16">
								<el-col :span="24">
									<el-form-item label="客户主诉">
										<el-input v-model="form.user_requirement" placeholder=""></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="主诉详情">
										<el-input v-model="form.user_requirement_remark" placeholder=""></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="检测场所">
										<el-input v-model="shop_info.shop_name" placeholder=""></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="检测人员">
										<el-input v-model="op_user_info.user_name" placeholder=""></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</div>
				</div>
				<div class="right">
					<div class="card card-1">
						<div class="title">足底扫描</div>
						<div class="image-box">
							<img src="@img/jianceImg.png" alt="" />
						</div>

						<div class="acitve">
							<el-button style="width: 100%" @click="clickBtns({ flag: '开始站位扫描' })" class="acitve-button-1">开始站位扫描</el-button>
							<el-button style="width: 100%" @click="clickBtns({ flag: '开始坐位扫描' })" class="acitve-button-1">开始坐位扫描</el-button>

							<!-- <el-button @click="clickBtns({ flag: '重置' })" class="acitve-button-2">重置</el-button> -->
						</div>
						<!-- <div class="desc">
							<div v-if="itemInfo.device_type != 3" class="box">
								<h4>操作说明</h4>
								<p>第一次检测：负重位（站立）</p>
								<p>第二次检测：休息位（坐位）</p>
								<p>全部检测完成后，点击"保存并退出”。</p>
							</div>
							<div v-else class="box">
								<h4>操作说明（足压板）</h4>
								<p>第一步：静态足压检测</p>
								<p>第二步：平衡态足压检测</p>
								<p>第三步：动态足压检测</p>
								<p>全部检测完成后，点击“保存并退出”。</p>
							</div>
						</div> -->
					</div>
				</div>
			</div>
			<div class="foot">
				<el-button @click="clickBtns({ flag: '取消检测' })" class="foot-button-1">取消检测</el-button>
				<el-button 
					@click="clickBtns({ flag: '保存并退出' })" 
					class="foot-button-2"
					:loading="sub_load"
					:disabled="sub_load"
				>
					{{ sub_load ? '正在提交请等待...' : '保存并退出' }}
				</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script>
import elDragDialog from '@/directives/el-drag-dialog'; // base on element-ui
import { calculateAge, formatDate, getNowFormatDate } from '@/utils/dateUtil.js';
export default {
	components: {},
	props: {
		info: {
			type: Object,
			default: () => {
				return { op_user_info: {} };
			}
		}
	},
	name: 'pagePop',
	data() {
		return {
			dialogVisible: false,
			sub_load: false,
			userinfo: this.info,
			form: {},
			op_user_info: {},
			shop_info: {},
			title: '',
			itemInfo: {}
		};
	},
	computed: {},
	watch: {
		info: {
			handler(val) {
				this.userinfo = {
					...val
				};
			},
			immediate: true
		}
	},
	created() {},
	mounted() {
		this.$socket.on('message', (data) => {
			console.log('在组件中收到消息:', data);
		});
	},
	methods: {
		clickBtns({ flag }) {
			if (flag == '开始站位扫描') {
				let strName = this.form.user_name;
				let genderMap = { 1: 0, 2: 1 }; // 1: '男' 2: '女'
				let strGender = genderMap[Number(this.form.gender)];
				let strPassword = '000000000000';
				let strCmd = `preparescan ${formatDate('yyyymmdd')} ${strName}-站 ${strGender} ${strPassword}`;
				// this.$socket.on('open', () => {
				this.$socket.send(strCmd);
				// });

				return;
			}
			if (flag == '开始坐位扫描') {
				let strName = this.form.user_name;
				let genderMap = { 1: 0, 2: 1 }; // 1: '男' 2: '女'
				let strGender = genderMap[Number(this.form.gender)];
				let strPassword = '000000000000';
				let strCmd = `preparescan ${formatDate('yyyymmdd')} ${strName}-坐 ${strGender} ${strPassword}`;
				// this.$socket.on('open', () => {
				this.$socket.send(strCmd);
				// });
				return;
			}
			if (flag == '保存并退出') {
				// 设置加载状态
				this.sub_load = true;
				
				let strName = this.form.user_name || '';
				console.log(strName, '------------strName');
				
				// 使用 Promise 来管理异步操作
				this.saveAndExit(strName).then(() => {
					console.log('保存操作完成');
					this.sub_load = false;
					this.handleClose();
				}).catch((error) => {
					console.error('保存操作失败:', error);
					this.sub_load = false;
					this.$message.error('保存失败，请重试');
				});

				return;
			}
			if (flag == '开始扫描') {
				return;
			}
			if (flag == '重置') {
				return;
			}
			if (flag == '取消检测') {
				// this.$socket.close(); // 关闭 WebSocket
				// this.$socket.connect('ws://127.0.0.1:1596/XsolWebRunScanner');
				// this.$socket.on('open', () => {
				this.$socket.send('exit');
				// });

				// this.$socket.connect('ws://localhost:8765');
				// this.$socket.send({
				// 	type: 'request',
				// 	action: 'exit',
				// 	device_id: 'XSOL'
				// });
				this.handleClose();
				return;
			}
		},
		init(data) {
			this.dialogVisible = true;
			if (data) {
				console.log({ ...data }, '----data');
				this.itemInfo = { ...data };
				let info = this.itemInfo?.info || {};
				this.form = { ...info.user_info };
				this.op_user_info = info.op_user_info;
				this.shop_info = info.shop_info;
				this.title = `${this.itemInfo.name}检测`;
			}
			this.$nextTick(() => {
				this.getCheckDetail();
				// this.$socket.close(); // 关闭 WebSocket
				// this.$socket.connect('ws://127.0.0.1:1596/XsolWebRunScanner');
			});
		},

		getCheckDetail() {
			let checkboxList = [];
			this.$api('check/config/check_kv', { keys: ['user_requirement'] }, 'post').then((res) => {
				if (res.code == 200) {
					checkboxList = res.data?.data?.user_requirement || [];
					this.$api('check/check_detail/detail', { check_id: this.$route.query.check_id }, 'post').then((res) => {
						if (res.code == 200) {
							let data = res.data.data;
							let user_requirement = data.user_requirement.split(',').map((v) => Number(v));
							let user_requirement_arr = [];
							user_requirement.map((id) => {
								let item = checkboxList.find((v) => v.id == id);
								user_requirement_arr.push(item.value);
							});
							this.$set(this.form, 'user_requirement', user_requirement_arr.join('，'));
							this.$set(this.form, 'user_requirement_remark', data.user_requirement_remark);
						}
					});
				}
			});
		},

		handleClose() {
			this.$emit('handleClose');
			this.form = {};
			this.$nextTick(() => {
				this.dialogVisible = false;
			});
		},
		
		// 保存并退出的异步方法
		saveAndExit(strName) {
			return new Promise((resolve, reject) => {
				// 计数器，用于跟踪发送的请求数量
				let sentCount = 0;
				let receivedCount = 0;
				const totalRequests = 2; // 总共需要发送2个请求
				
				// 超时处理
				const timeout = setTimeout(() => {
					reject(new Error('保存操作超时'));
				}, 60000); // 60秒超时
				
				this.$socket.close(); // 关闭 WebSocket
				this.$socket.connect('ws://localhost:8765');
				
				this.$socket.on('open', () => {
					// 发送第一个请求
					this.$socket.send({
						command: 'save',
						device_type: 'XSOL', // 设备类型
						user_id: this.$route.query.user_id,
						device_id: this.itemInfo.id, // 设备ID
						check_id: this.$route.query.check_id,
						user_name: `${strName}-站` // 用户名-检查类型
					});
					sentCount++;
					console.log(`已发送第 ${sentCount} 个请求: ${strName}-站`);
					
					// 发送第二个请求
					this.$socket.send({
						command: 'save',
						device_type: 'XSOL', // 设备类型
						user_id: this.$route.query.user_id,
						device_id: this.itemInfo.id, // 设备ID
						check_id: this.$route.query.check_id,
						user_name: `${strName}-坐` // 用户名-检查类型
					});
					sentCount++;
					console.log(`已发送第 ${sentCount} 个请求: ${strName}-坐`);
					
					console.log('所有请求已发送完成');
				});
				
				// 监听消息响应
				this.$socket.on('message', (data) => {
					receivedCount++;
					console.log(`收到第 ${receivedCount} 个响应:`, data);
					
					// 当收到所有响应后，延迟关闭
					if (receivedCount >= totalRequests) {
						console.log('所有响应已收到，准备关闭');
						clearTimeout(timeout); // 清除超时
						
						// 延迟1秒后完成
						setTimeout(() => {
							resolve();
						}, 1000);
					}
				});
				
				// 错误处理
				this.$socket.on('error', (error) => {
					clearTimeout(timeout);
					reject(error);
				});
			});
		}
	},
	beforeDestroy() {
		// this.$socket.close(); // 关闭 WebSocket
		this.sub_load = false; // 重置加载状态
		
		// 清理 socket 事件监听器
		if (this.$socket) {
			this.$socket.off('message');
			this.$socket.off('error');
			this.$socket.off('open');
		}
	}
};
</script>

<style lang="less">
.pagePop {
	// width: fit-content !important;
	// border-radius: 8px;
	overflow: hidden;
	.el-dialog__header {
		// .bor();
		padding: 0;
	}
	.el-dialog__body {
		padding: 0;
		// max-height: 70vh;
		// overflow-y: auto;
	}
	.inner {
		// display: flex;
		// justify-content: center;
		// flex-direction: column;
		// align-items: center;
		.body {
			padding: 47px 100px 0;
			width: 1400px;
			margin: auto;
			background: #fff;
			display: flex;
			gap: 30px;
			.card {
				padding: 25px;
				.title {
					padding-bottom: 15px;
					font-weight: bold;
					font-size: 18px;
					color: #333333;
					line-height: 25px;
					text-align: left;
					font-style: normal;
				}
				.custom-form.el-form--label-top {
					.el-form-item {
						margin-bottom: 20px;
						.el-form-item__label {
							padding: 0;
						}
					}
				}
			}

			.left {
				.card-1 {
					width: 568px;
					height: 369px;
					background: #fafafa;
					border-radius: 10px;
				}
				.card-2 {
					margin-top: 34px;
					width: 568px;
					height: 460px;
					background: #fafafa;
					border-radius: 10px;
				}
			}
			.right {
				.card-1 {
					padding: 25px;
					width: 597px;
					height: 863px;
					background: #fafafa;
					border-radius: 10px;
					.title {
						padding-bottom: 32px;
					}
					.image-box {
						width: 547px;
						height: 441px;
						background: #070707;
						border-radius: 10px;
						img {
							width: 100%;
							height: 100%;
						}
					}
					.desc {
						display: flex;
						justify-content: space-between;
						margin-top: 23px;
						width: 547px;
						// height: 216px;
						background: #ffffff;
						border-radius: 10px;

						padding: 25px 10px;
						font-size: 14px;
						color: #333333;
						line-height: 27px;
						text-align: left;
						font-style: normal;
						.box {
						}
					}
					.acitve {
						margin-top: 23px;
						display: flex;
						flex-direction: column;
						gap: 10px;
						button {
							margin: 0;
						}
						.acitve-button-1 {
							// width: 262px;
							flex: 1;
							height: 50px;
							background: #fc5f10;
							border-radius: 10px;
							border: 1px solid #ffffff;

							font-weight: bold;
							font-size: 16px;
							color: #ffffff;
							line-height: 22px;
							font-style: normal;
						}
						.acitve-button-2 {
							width: 262px;
							height: 50px;
							background: #c3c3c3;
							border-radius: 10px;
							border: 1px solid #ffffff;

							font-weight: bold;
							font-size: 16px;
							color: #ffffff;
							line-height: 22px;
							font-style: normal;
						}
					}
				}
			}
		}
		.foot {
			padding: 25px 130px;
			text-align: right;
			.foot-button-1 {
				width: 262px;
				height: 60px;
				background: #bababa;
				border-radius: 10px;
				font-weight: bold;
				font-size: 16px;
				color: #ffffff;
				line-height: 22px;
				font-style: normal;
			}
			.foot-button-2 {
				width: 262px;
				height: 60px;
				background: #21c55d;
				border-radius: 10px;
				font-weight: bold;
				font-size: 16px;
				color: #ffffff;
				line-height: 22px;
				font-style: normal;
				
				// 加载状态样式
				&.is-loading {
					background: #21c55d !important;
					color: #ffffff !important;
					border-color: #21c55d !important;
				}
				
				&:disabled {
					background: #21c55d !important;
					color: #ffffff !important;
					border-color: #21c55d !important;
					opacity: 0.8;
				}
			}
		}
		.head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 35px;

			height: 94px;
			background: #fafafa;
			.left {
				display: flex;
				align-items: center;
				.icon {
				}
				span {
					font-weight: bold;
					font-size: 18px;
					color: #333333;
					line-height: 25px;
					text-align: left;
					font-style: normal;
				}
			}
			.right {
				display: flex;
				.right-button-1 {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 62px;
					height: 32px;
					background: #21c55d;
					border-radius: 6px;
					font-weight: 500;
					font-size: 14px;
					color: #ffffff;
					font-style: normal;
				}
				.right-button-2 {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 62px;
					height: 32px;
					background: #f31a1a;
					border-radius: 6px;
					font-weight: 500;
					font-size: 14px;
					color: #ffffff;
					font-style: normal;
				}
			}
		}
	}
}
</style>
